import React, { Component } from 'react'
import { Row, Col, Input, Select, Button, Modal, DatePicker } from 'antd';
import { Form } from '../../common/form';
import { TablePage } from '../../common/table-page';
import { connectRouter } from '../../../mixins/router';
const TableColumn = TablePage.Column;
import history from '../../../history'
import api from '../../../api/api';
import { testPermission } from '../../common/HasPermission';

const StatusChoices = [{
    value: '10',
    label: '待确认',
}, {
    value: '20',
    label: '投保中',
}, {
    value: '30',
    label: '已承保',
}, {
    value: '40',
    label: '已完成',
}];

const QueryKeyChoices = [{
    value: 'policyNo',
    label: '保单号',
    placeholder: '请输入保单号',
}, {
    value: 'sequenceNo',
    label: '投保单流水号',
    placeholder: '请输入投保单流水号',
}];

const mapChoiceToOption = (choice, i) => <Select.Option key={i} value={choice.value}>{choice.label}</Select.Option>;

const tableDef = TablePage.def({
    queryKey: {
        parse: val => val || 'policyNo',
        stringify: val => val === 'policyNo' ? undefined : val
    },
    queryText: {},
    status: {},
});
const query = {
    sequenceNo:'',
    policyNo:'',
    status:'',
    skip:0,
    limit:11,
  }
class GroupOrderInsurance extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      insurId: null,
      confirmDate: null,
      confirmDateExplain: null,
      insurOrderNoExplain: null,
      groupOrderData: {},
    };
  }
  componentWillReceiveProps(nextProps) {}

  componentWillUnmount() {
    // this.props.resetGroupInsurances();
  }

  loadData = ({ values, pageIndex, pageSize }) => {
    const query = {};

    pageIndex = pageIndex || 1;
    pageSize = pageSize || 10;
    let skip = (pageIndex - 1) * pageSize;
    query.skip = skip < 0 ? 0 : skip;
    query.limit = pageSize + 1;

    if (values.queryKey && values.queryText) {
      query[values.queryKey] = values.queryText;
    }
    if (values.status) {
      query.status = values.status;
    }

    this.getGroupInsuranceList(query);
  };

  getGroupInsuranceList = async (query) => {
    let router = this.props.router;
    let groupOrderData = {};
    let result = await api.getGroupInsurances(query);

    if (result) {
      let pageIndex = +router.query.p || 1;
      let pageSize = +router.query.ps || 10;
      groupOrderData.status = 'fulfilled';
      groupOrderData.pageIndex = pageIndex;
      groupOrderData.pageSize = pageSize;
      groupOrderData.count = (pageIndex - 1) * pageSize + result.length;
      if (result.length > pageSize) {
        result = result.slice(0, -1);
      }
      groupOrderData.list = result;
      this.setState({
        groupOrderData,
      });
    }
  };

  resetData = () => {
    let router = this.props.router;
    let pageIndex = +router.query.p || 1;
    let pageSize = +router.query.ps || 10;
    let skip = (pageIndex - 1) * pageSize;
    query.skip = skip < 0 ? 0 : skip;
    query.limit = pageSize + 1;
    this.getGroupInsuranceList(query);
  };
  // 团险订单管理
  buyGroupInsurance = () => {
    // 团险投保
    history.push(`/BuyGroupInsurance?r=${encodeURIComponent(this.props.router.fullPath)}`);
  };

  // 上传承保清单按钮
  GroupUnderwriting = () => {
    history.push(`/GroupUnderwritingList?r=${encodeURIComponent(this.props.router.fullPath)}`);
  };

  // 查看团险详情
  showDetail = (insurance) => {
    history.push(`/GroupOrderInsuranceDetail/${insurance.id}?productId=${insurance.productId}&r=${encodeURIComponent(this.props.router.fullPath)}`);
  };
  // 提交保险
  updateInsurance = (insurance) => {
    history.push(`/BuyGroupInsurance/?id=${insurance.id}&productId=${insurance.productId}`);
    // this.props.router.openModal('newGroupInsurance', insurance.insurId);
  };
  // 导出保险清单
  exportList = (id) => {
    window.open(`_api/groupInsurance/${id}/insuranceTeamOrderInfo`);
  };

  // 投保清单模板下载
  downloadTemplate = () => {
    window.open(
      'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/crm-web/groupOrderInsurance/%E6%8A%95%E4%BF%9D%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx',
    );
  };

  downloadTemplate1 = () => {
    window.open(
      'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/crm-web/groupOrderInsurance/%E6%89%BF%E4%BF%9D%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF%281%29.xlsx',
    );
  };

  render() {
    const { groupOrderData } = this.state;
    return (
      <div>
        <TablePage
          def={tableDef}
          data={groupOrderData}
          autoLoad={false}
          onLoadData={this.loadData}
          onResetData={this.resetData}
          tableRef={(table) => (this.table = table)}
          rowKey="id"
          renderFormFields={(values, loadData) => {
            let searchProps;
            const selectedItem = QueryKeyChoices.find((item) => item.value === values.queryKey);
            searchProps = { placeholder: selectedItem.placeholder || '' };
            return (
              <Row gutter={10} className="block filter-box">
                <Col span={3} key="1">
                  <Form.Item field="queryKey" height="auto">
                    <Select>{QueryKeyChoices.map(mapChoiceToOption)}</Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item field="queryText" height="auto">
                    <Input {...searchProps} onPressEnter={loadData} maxLength={'100'} />
                  </Form.Item>
                </Col>
                <Col span={4}>
                  <Form.Item field="status" height="auto">
                    <Select placeholder="投保单状态" allowClear>
                      {StatusChoices.map(mapChoiceToOption)}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <Button onClick={loadData} style={{ width: '100%', minWidth: 0 }} type="primary">
                    查询
                  </Button>
                </Col>
                {testPermission('groupInsurance.insure') ? (
                  <Col span={3}>
                    <Button onClick={this.buyGroupInsurance} style={{ width: '100%', minWidth: 0 }} type="primary">
                      上传投保清单
                    </Button>
                  </Col>
                ) : (
                  ''
                )}
                {testPermission('groupInsurance.insure') ? (
                  <Col span={3}>
                    <Button onClick={this.GroupUnderwriting} style={{ width: '100%', minWidth: 0 }} type="primary">
                      上传承保清单
                    </Button>
                  </Col>
                ) : (
                  ''
                )}
              </Row>
            );
          }}
        >
          <TableColumn
            title="投保单流水号"
            className="singleline max-w-200"
            dataIndex="sequenceNo"
            key="sequenceNo"
            onCellClick={(insurance) => this.showDetail(insurance)}
            render={(text, insurance) => (insurance.status === 0 ? text : <span className="clickable">{text}</span>)}
          />
          <TableColumn title="保单号" className="singleline max-w-200" dataIndex="policyNo" key="policyNo" />
          <TableColumn title="保险公司" className="singleline" dataIndex="insuranceCompany" key="insuranceCompany" />
          <TableColumn
            title="投保商品(代码)"
            className="singleline"
            dataIndex="productName"
            key="productName"
            render={(text, insurance) => {
              return (
                <div>
                  <div>
                    {text}({insurance.productCode})
                  </div>
                  <div className="pro-note">{insurance.note}</div>
                </div>
              );
            }}
          />
          <TableColumn
            title="保险期间"
            className="singleline"
            dataIndex="startDate"
            key="startDate"
            render={(text, insurance) => {
              return (
                <div>
                  {text}至{insurance.endDate}
                </div>
              );
            }}
          />
          <TableColumn title="缴费期数" className="singleline" dataIndex="paymentPeroid" key="paymentPeroid" />
          <TableColumn title="投保主体" className="singleline" dataIndex="insurerName" key="insurerName" />
          <TableColumn
            title="投保单状态"
            className="singleline"
            dataIndex="status"
            key="status"
            render={(status) => {
              if (status === null || status === undefined) return '';
              const found = StatusChoices.find((t) => t.value === `${status}`);
              if (found) {
                return found.label;
              }
              return '未知状态';
            }}
          />
          <TableColumn title="提交时间" className="singleline" dataIndex="createDate" key="createDate" />
          {testPermission('groupInsurance.export') || testPermission('groupInsurance.insure') ? (
            <TableColumn
              title="操作"
              className="singleline"
              dataIndex="status"
              key="op"
              renderTip={() => null}
              render={(status, insurance) => {
                let toggleBtn;
                if (status == 10) {
                  toggleBtn = (
                    <span>
                      {testPermission('groupInsurance.insure') ? (
                        <span className="clickable" onClick={() => this.updateInsurance(insurance)}>
                          提交
                        </span>
                      ) : null}
                    </span>
                  );
                } else if (status == 20 || status == 30 || status == 40) {
                  if (testPermission('groupInsurance.export')) {
                    toggleBtn = (
                      <span>
                        <span className="clickable" onClick={() => this.exportList(insurance.id)}>
                          导出清单
                        </span>
                      </span>
                    );
                  }
                }
                return toggleBtn;
              }}
            />
          ) : null}
        </TablePage>
        <div className="download" style={{ marginTop: '10px' }}>
          <Button onClick={this.downloadTemplate}>投保清单模板下载</Button>
          <Button style={{marginLeft: '10px'}} onClick={this.downloadTemplate1}>承保导入模板下载</Button>
        </div>
      </div>
    );
  }
}

export default connectRouter(GroupOrderInsurance);
